package com.forum.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@WebFilter("/forum/*")
public class AuthFilter implements Filter {

    private static final String WHITE = "/login";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        System.out.println("执行过滤器");
        try {
            // 如果路径在白名单中则直接放行
            String path = request.getServletPath();
            if(path.contains(WHITE)) {
                filterChain.doFilter(request, response);
                return;
            }
            String token = request.getHeader("token");
            // 如果token不在redis缓存中，过滤
            if(redisTemplate.opsForValue().get(token) == null) {
                response.setStatus(401);
                return ;
            }
            System.out.println(456);
            filterChain.doFilter(request, response);
        } catch (Exception e) {

        }
    }
}
